package com.lili.other;

import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2024/8/24
 * @Description: 535. TinyURL的加密与解密
 * @version: 1.0
 */
public class Codec {
    private Map<String, String> longToShort = new HashMap<>();

    private Map<String, String> shortToLong = new HashMap<>();

    private static final String SHORT_PREFIX = "http://tinyurl.com/";

    private static int id = 1;

    public String encode(String longUrl) {
        String shortUrl = longToShort.get(longUrl);
        if (shortUrl != null) {
            return shortUrl;
        }
        //生成短网址
        /*
         * 1.用随机数生成短网址标识
         * 2.用[hash]码作为短网址标识
         * 3.用[递增数]作为短网址标识
         * */
        //1.用随机数生成短网址标识
//        while (true) {
//            int id = ThreadLocalRandom.current().nextInt();
//            shortUrl = SHORT_PREFIX + id;
//            if (!shortToLong.containsKey(shortUrl)) {
//                longToShort.put(longUrl, shortUrl);
//                shortToLong.put(shortUrl, longUrl);
//                break;
//            }
//        }
        //2.用[hash]码作为短网址标识
//        int id = longUrl.hashCode();
//        while (true) {
//            shortUrl = SHORT_PREFIX + id;
//            if (!shortToLong.containsKey(shortUrl)) {
//                longToShort.put(longUrl, shortUrl);
//                shortToLong.put(shortUrl, longUrl);
//                break;
//            }
//            id++;
//        }


        shortUrl = SHORT_PREFIX + id;
        longToShort.put(longUrl, shortUrl);
        shortToLong.put(shortUrl, longUrl);
        id++;
        return shortUrl;
    }


    public String decode(String shortUrl) {
        return shortToLong.get(shortUrl);
    }
}
